package com.easylinkin.linkappapi.facerecognition.config;

import com.easylinkin.linkappapi.facerecognition.service.rest.KoalaManagementClientService;
import com.easylinkin.linkappapi.facerecognition.service.rest.KoalaRecognizeClientService;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@ConditionalOnProperty(value = "ai.face.platform", havingValue = "koala")
public class KoalaRestClientConfig {

    @Value("${ai.face.koala.management}")
    private String faceManagementUrl;

    @Value("${ai.face.koala.recognize}")
    private String faceRecognizeUrl;

    private ConcurrentHashMap<String, List<Cookie>> cookieStore = new ConcurrentHashMap<>();

    @Bean
    public KoalaManagementClientService koalaManagementClient(OkHttpClient client) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(faceManagementUrl.endsWith("/") ? faceManagementUrl : (faceManagementUrl + "/"))
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(KoalaManagementClientService.class);
    }

    @Bean
    public KoalaRecognizeClientService koalaRecognizeClient(OkHttpClient client) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(faceRecognizeUrl.endsWith("/") ? faceRecognizeUrl : (faceRecognizeUrl + "/"))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit.create(KoalaRecognizeClientService.class);
    }

    @Bean
    OkHttpClient client() {

        return new OkHttpClient.Builder()
                // koala  的接口需要使用cookie来完成鉴权
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                        cookieStore.put(httpUrl.host(), list);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                        List<Cookie> cookies = cookieStore.get(httpUrl.host());
                        return cookies != null ? cookies : new ArrayList<>();
                    }
                })
                .build();
    }

}
